package com.ck567.netty.chatroom.server.handler

import ch.qos.logback.classic.turbo.TurboFilter
import com.ck567.netty.chatroom.message.GroupChatRequestMessage
import com.ck567.netty.chatroom.message.GroupChatResponseMessage
import com.ck567.netty.chatroom.server.session.GroupSessionFactory
import com.ck567.netty.chatroom.util.logger
import io.netty.channel.ChannelHandler
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler

@ChannelHandler.Sharable
class GroupChatMessageHandler : SimpleChannelInboundHandler<GroupChatRequestMessage>() {
    override fun channelRead0(ctx: ChannelHandlerContext, msg: GroupChatRequestMessage) {
        logger.info("==================")
        logger.info("群发消息：$msg")
        val members = GroupSessionFactory.getSession().getMembersChannel(msg.name)
        members?.forEach { channel ->
            if (channel != ctx.channel()) {
                channel.writeAndFlush(GroupChatResponseMessage(true, "接收到消息！", msg.from, msg.content))
            }
        }
        ctx.writeAndFlush(GroupChatResponseMessage(true, "群发成功！", "", ""))
    }

    companion object {
        private val logger = logger<GroupChatMessageHandler>()
    }
}